package pres.hdy.htmltopdf.config;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import freemarker.cache.TemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import freemarker.template.Version;

public class TemplateConfig extends ItextRenderConfig{

	private Configuration configuration;


	private String encoding;

	public void setTemplateLoader(TemplateLoader templateLoader) {
		this.configuration.setTemplateLoader(templateLoader);
	}

	public TemplateConfig() {
		this(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
	}

	public TemplateConfig(Configuration configuration) {
		this.configuration = configuration;
	}

	public TemplateConfig(Version v) {
		this.configuration = createConfig(v);
	}

	public Document getDocument(String path, Object mapping) {
		Document doc = null;
		StringWriter s = new StringWriter();
		try (BufferedWriter b = new BufferedWriter(s)) {
			Template template = this.configuration.getTemplate(path);
			template.process(mapping, b);
			byte[] bytes = null;
			if (this.encoding != null)
				bytes = s.toString().getBytes(this.encoding);
			else
				bytes = s.toString().getBytes();
			doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(bytes));
		} catch (TemplateNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
		this.configuration.setDefaultEncoding(encoding);
	}

	protected Configuration createConfig(Version v) {
		Configuration c = new Configuration(v);
		return c;
	}

}
